<template>
  <div class="employees-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录条数{{ total }}</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button v-allow="'import_excel'" round type="warning" size="small" @click="$router.push('/employees/import')">导入 Excel </el-button>
          <el-button v-allow="'export_excel'" round type="danger" size="small" @click="hExport">导出 Excel </el-button>
          <el-button round type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{ row }">
              <img-holder class="avatar" :src="row.staffPhoto" alt="" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              <!-- {{ row.formOfEmployment }} -->
              {{ formatEmpolyees(row.formOfEmployment) }}
              <!-- {{ row.formOfEmployment }} -->
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortablej label="入职时间">
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <!-- <el-button
                type="text"
                @click="$router.push({
                  path: '/employees/detail',
                  query: {id: row.id}
                })"
              >查看</el-button> -->
              <el-button
                type="text"
                @click="$router.push('/employees/detail/' + row.id)"
              >查看</el-button>
              <el-button type="text" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="q.page"
            :page-sizes="[5, 10, 20, 25]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
    <!-- 新增员工弹框 -->
    <el-dialog
      :visible.sync="showDialog"
      title="新增员工"
      width="45%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @closed="hClosed"
    >
      <emp-dialog ref="empDialog" @close="showDialog=false" @hSuccess="success" />
    </el-dialog>

    <!-- 分配角色弹框 -->
    <el-dialog
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
      @closed="$refs.AssignRole.resetArr()"
    >
      <assign-role :id="curId" ref="AssignRole" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import empDialog from './empDialog.vue'
import { deleteEmployees, getEmployees } from '@/api/employees'
import employeesCode from '@/constant/employees'
import AssignRole from './assignRole.vue'

// 准备一个映射对象, 最终目标是: { 1: '正式', 2: '非正式' }
const hireTypeMap = {}
// 可选作业: 把 forEach 变成 reduce
// 执行循环后达成目标: { 1: '正式', 2: '非正式' }
employeesCode.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})

export default {
  name: 'DeptDialog',
  components: { empDialog, AssignRole },
  data() {
    return {
      employees: [],
      q: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false,
      showDialogRole: false,
      curId: ''
      // employeesMap: {}
    }
  },
  created() {
    this.loadEmpoyees()
    /* employeesCode.hireType.forEach(item => {
      this.employeesMap[item.id] = item.value
    }) */
  },
  methods: {
    async loadEmpoyees() {
      const res = await getEmployees(this.q)
      // console.log(res)
      this.employees = res.data.rows
      this.total = res.data.total
    },
    formatEmpolyees(code) {
      return hireTypeMap[code]
      /* const result = employeesCode.hireType.find(item => item.id === +code) // 返回对应的对象
      if (result) {
        // console.log(result)
        return result.value
      } else {
        // console.log(1)
        return '未知'
      } */
    },
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmpoyees()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmpoyees()
    },
    // 删除功能
    async hDel(id) {
      try {
        // 删除提示框
        await this.$confirm('您确定要删除吗？', '提示', { type: 'warning' })
        // 发送请求
        const res = await deleteEmployees(id)
        // 成功删除提示
        this.$message.success(res.message)
        // 如果是当前页面只剩下最后一条则将页面减1
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        // 重新更新
        this.loadEmpoyees()
      } catch (e) {
        // console.log(e) 精细化处理
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    success() {
      this.showDialog = false
      // 如果当前页面添加满了，在添加就自动跳转到下一页
      if (this.total % this.q.size === 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmpoyees()
    },
    formatDate(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    hClosed() {
      this.$refs.empDialog.resetForm()
    },
    async hExport() {
      const res = await getEmployees({ page: 1, size: this.total })
      // console.log(res)
      const list = res.data.rows
      /* const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const zhList = list.map(enObj => {
        Object.keys
      }) */
      /* const first = zhList[0]
      if (!first) return
      const header = Object.keys(first)
      const data = zhList.map(item => {
        const code = item['聘用形式']
        item['聘用形式'] = hireTypeMap[code]
        return Object.values(item)
      }) */
      const { header, data } = this.formatData(list)
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header,
        data,
        filename: '员工数据',
        autoWidth: true,
        bookType: 'xlsx'
      })
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireTypeMap[key] // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    hAssign(id) {
      // console.log('获取分配角色的id', id)
      this.curId = id
      this.showDialogRole = true
      // 调用子组件里的方法重新获取最新数据
      this.$nextTick(() => {
        this.$refs.AssignRole.loadRolesDetailById()
      })
    }
  }
}
</script>

<style scoped>
  .el-pagination {
    height: 60px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
</style>
